from django.shortcuts import render

from django.shortcuts import render, HttpResponse, redirect
from hcw_models.models import *
from hcw_models.models import MyUser
import re
from hcw_models.forms import *
from django.contrib.auth import logout
from django.contrib import auth

from django.contrib.auth.hashers import make_password, check_password

# Create your views here.

from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger


def show_subject(page_id, subjects):
    # .order_by("no”)
    # 使用Paginator模块对数据分页，一页5条数据
    paginator = Paginator(subjects, 1)
    # 使用request.GET.get()函数获取uri中的page参数的数值
    page = page_id
    try:
        # 通过获取上面的page参数，查询此page是否为整数并且是否可用
        print ("1")
        subject_obj = paginator.page(page)
    except PageNotAnInteger:
        print ("2")

        subject_obj = paginator.page(1)
    except (EmptyPage, InvalidPage):
        print ("3")

        subject_obj = paginator.page(paginator.num_pages)
    print (page, subject_obj)
    return subject_obj
    #  render(request, "subject.html", {'subject_list': subject_obj})


def index(request):
    # articleClass= ArticleClass.objects.all()  # 通过category查出所有分类
    # banner = Banner.objects.all()[0:8]
    tui = Tui.objects.all()  # 查询推荐位IO为1的文章
    # _tui={}
    # for t in tui:
    #     _tui[t.name]=t.tuiKey.all()
    # allarticle = Article.objects.all().order_by('-id')[0:10]
    _pass = ""
    # # 热门文章排行实现
    # # hot = Article.objects.all().order_by('?')[:10]#随机推荐
    # # hot = Article.objects.filter(tui_id=3)[:10]   #通过推荐进行查询，以推荐ID是3为例
    # hot = Article.objects.all().order_by('views')[:10]  # 通过浏览数进行排序
    # # 右侧热门推荐实现
    # remen = Article.objects.filter(tui__id=1)[:6]

    # # 右侧所有标签实现
    # tags = Tag.objects.all()
    search_status = False

    search = request.GET.get("search")

    page = request.GET.get("page")

    tui_id = request.GET.get("tui_id")
    if tui_id == None:
        subjects = Article.objects.filter(status="p").order_by("id")
    else:
        subjects = Article.objects.filter(
            tui=tui_id, status="p").order_by("id")
        _pass = "tui_id=%s" % tui_id

        print ("==========", _pass)

    if search != None:
        search_status = True
        subjects = Article.objects.filter(
            content__contains=search, status="p").order_by("id")
        if len(subjects) == 0:
            print ("通过标题搜索")
            try:
                subjects = Article.objects.filter(
                    title__contains=search).order_by("id")
            except:
                pass
        if len(subjects) == 0:

            print ("通过摘要查找")
            try:

                subjects = Article.objects.filter(
                    excerpt__contains=search).order_by("id")
            except:
                pass

        if len(subjects) == 0:
            print ("通过用户查找")
            try:
                subjects = Article.objects.filter(
                    user__contains=search, status="p").order_by("id")
                print (subjects)

            except:
                pass
        if len(subjects) == 0:
            print ("通过分类查找")
            try:
                subjects = Article.objects.filter(
                    Class__contains=search, status="p").order_by("id")
            except:
                pass
        _pass = "search=%s" % search

    # links = Link.objects.all()

    # # # 封装到上下文
    context = {
        # 'articleClass': articleClass,
        # 'banner': banner,
        'tui': tui,
        # 'allarticle': allarticle,
        # 'hot': hot,
        # 'remen': remen,
        # 'tags': tags,
        'pass': _pass,
        'search_status': search_status,
        'subject_list': show_subject(page, subjects),
        'title': "首页"
    }
    print ("首页")
    return render(request, 'index.html', context)


def list(request, lid):
    list = Article.objects.filter(category_id=lid)  # 通过URL传进来的lid筛选文章
    cname = ArticleClass.objects.get(id=lid)  # 获取文章的栏目名
    allcategory = ArticleClass.objects.all()  # 导航栏所有类
    tags = Tag.objects.all()  # 右侧所有文章标签
    # locals()代替了context，locals()的作用是返回一个包含当前作用域里面的所有变量和它们的值的字典。

    # 右侧热门推荐实现
    remen = Article.objects.filter(tui__id=1)[:6]

    # 文章分页
    page = request.GET.get('page')  # 从URL中获取当前页面页数
    paginator = Paginator(list, 5)  # 对当前查询到的数据对象进行分页，5条一页
    try:
        list = paginator.page(page)  # 获取当前页码的记录
    except PageNotAnInteger:
        list = paginator.page(1)  # 如果用户输入页码不是整数，显示第一页
    except EmptyPage:
        list = paginator.page(paginator.num_pages)  # 若果用户输入的页数不在系统的页码中，显示最后一页

    return render(request, 'list.html', locals())


def show(request, sid):
    show = Article.objects.get(id=sid)  # 获取指定id的文章
    allcategory = ArticleClass.objects.all()
    tags = Tag.objects.all()
    remen = Article.objects.filter(tui_id=1)[:6]  # 右侧热门
    hot = Article.objects.all().order_by('?')[:10]  # 随机推荐
    previous_blog = Article.objects.filter(created_time__gt=show.created_time,
                                           category=show.category.id).first()
    next_blog = Article.objects.filter(
        created_time__lt=show.created_time, category=show.category.id).last()
    show.views = show.views + 1  # 浏览量
    show.save()
    show.content = markdown.markdown(show.content,
                                     extensions=[
                                         'markdown.extensions.extra',
                                         'markdown.extensions.codehilite',
                                         'markdown.extensions.toc',
                                     ])
    return render(request, 'show.html', locals())


def tag(request, tag):
    list = Article.objects.filter(tags__name=tag)  # 通过文章标签进行查询
    remen = Article.objects.filter(tui__id=1)[:6]
    allcategory = Category.objects.all()
    tname = Tag.objects.get(name=tag)  # 获取当前搜索的标签名
    page = request.GET.get('page')  # 分页
    tags = Tag.objects.all()
    paginator = Paginator(list, 5)
    try:
        list = paginator.page(page)  # 获取当前页码的记录
    except PageNotAnInteger:
        list = paginator.page(1)  # 如果用户输入页码不是整数，显示第一页
    except EmptyPage:
        list = paginator.page(paginator.num_pages)  # 若果用户输入的页数不在系统的页码中，显示最后一页

    return render(request, 'tags.html', locals())


def search(request):
    ss = request.GET.get('search')  # 获取搜索的关键词
    list = Article.objects.filter(
        title__icontains=ss).order_by('id')  # 获取到搜索关键词通过标题进行匹配
    remen = Article.objects.filter(tui__id=1)[:6]
    allcategory = Category.objects.all()
    page = request.GET.get('page')
    tags = Tag.objects.all()
    paginator = Paginator(list, 10)
    try:
        list = paginator.page(page)  # 获取当前页码记录
    except PageNotAnInteger:
        list = paginator.page(1)  # 如果用户输入页码不是整数，显示第一页
    except EmptyPage:
        list = paginator.page(paginator.num_pages)  # 若果用户输入的页数不在系统的页码中，显示最后一页

    return render(request, 'search.html', locals())


# 关于我们
def about(request):
    allcategory = Category.objects.all()
    return render(request, 'page.html', locals())


def userinfo(request):
    us=request.GET.get("username")

    if us == None:

        u = MyUser.objects.get(username=request.user)
    else:
        u = MyUser.objects.get(username=us)



    context = {
        'data': u,
        'form': MyUserForm(instance=u),
        'title': "用户信息",
        'request_user': str(request.user),
    }

    if request.method == "POST":
        f = MyUserForm(instance=request.user,
                       data=request.POST, files=request.FILES)
        print (f.is_valid())
        print (f.errors)
        f.save()

        return redirect("/userinfo/")

    return render(request, 'userinfo.html', context)


def upPwd(request):
    u = MyUser.objects.get(username=request.user)

    context = {
        'data': {"img": u.img, "username": u.username, "password": u.password},
        'form': MyUserForm(instance=u),
        'title': "密码修改"
    }
    if request.method == "POST":

        pwd = request.POST["password"]

        _p = re.compile(r'[a-zA-Z].*[0-9]{6,12}')
        if not _p.match(pwd):
            return HttpResponse("密码不符合要求: 6到12位 大小写字母开头  包含数字")

        # 创建django密码，第三个参数为加密算法
        mpwd = make_password(pwd, None, 'pbkdf2_sha256')
        u.password = mpwd
        u.save()
        return redirect("/")

    return render(request, 'upPwd.html', context)


def ArticleAdmin(request):

    context = {
        'title': "文章管理"
    }

    context["Article"] = Article.objects.filter(user=request.user)
    return render(request, 'ArticleAdmin.html', context)


def userlogout(request):
    logout(request)

    return redirect("/")


def user_auths(request):
    s = {}
    s["status"] = False
    u = request.POST['username']
    p = request.POST['password']
    print (u, p)
    if u == '' or p == '':
        print ("账号或密码输入不合法")
        s["msg"] = "账号或密码输入不合法"
        return s
    if not MyUser.objects.filter(username=u):
        s["msg"] = "用户不存在"
        s["status"] = True
        return s

    else:
        user_obj = auth.authenticate(username=u, password=p)
        s["status"] = True
        s["obj"] = user_obj
        s["msg"] = "用户存在密码错误"
        return s


def userlogin(request):

    user_obj = user_auths(request)
    if user_obj["status"] == True:
        if not user_obj["obj"]:
            return HttpResponse(user_obj["msg"])
        else:
            auth.login(request, user_obj["obj"])
            return redirect("/")
    else:

        return HttpResponse(user_obj["msg"])


def addArticle(request):

    context = {

        'ArticleForm': ArticleForm,
        'title': "写文章"
    }
    print ("===添加文章")

    if request.method == "POST":
        title = request.POST.get("title")
        excerpt = request.POST.get("excerpt")
        content = request.POST.get("content")
        Class = request.POST.get("Class")
        status = request.POST.get("status")
        print ("状态", status)
        c = ArticleClass.objects.get(id=Class)
        t = Tui.objects.get(name="其他")

        Article(title=title, excerpt=excerpt, content=content, Class=c,
                status=status, tui=t, user=request.user).save()

        # print ("===",'发布',f.data)
        # print (f.is_valid())
        # print (f.errors)
        # f.save()

        return redirect("/")

    return render(request, 'addArticle.html', context)


def showArticle(request):

    context = {
        'commentForm': commentForm,
        'title': "查看文章"
    }

    _id = request.GET.get("id")

    a = Article.objects.get(id=_id)
    if str(request.user) != a.user:
        a.views += 1
        a.save()
    context["Article"] = a
    context["ArticleClass"] = ArticleClass.objects.get(
        name=a.Class).classKey.all()
    context["request_user"] = str(request.user)

    context["comment"] = {
        "count": a.ArticleCommentKey.all().count(),
        "comment_list": a.ArticleCommentKey.all()
    }

    return render(request, 'showArticle.html', context)


def delArticle(request):

    context = {

        'title': "删除文章"
    }

    _id = request.GET.get("id")
    print (_id)
    a = Article.objects.filter(id=_id, user=request.user).delete()

    return redirect("/ArticleAdmin/")


def comments(request):
    context = {

        'title': "评论"
    }
    if request.method == "POST":

        print (request.user)
        _id = request.POST.get("id")
        content = request.POST.get("content")
        a = Article.objects.get(id=_id)
        comment(user=request.user, content=content, ArticleComment=a).save()

        return HttpResponse("评论成功")

    # a=Article.objects.get(id=_id,user=request.user).delete()


def upArticle(request):

    context = {

        'title': "修改文章"
    }
    if request.method == "POST":
        _id = request.POST.get("id")
        a = Article.objects.get(id=_id, user=request.user)
        f = ArticleForm(data=request.POST, instance=a)
        print (f.is_valid())
        print (f.errors)
        f.save()

        return redirect("/ArticleAdmin/")

    _id = request.GET.get("id")
    a = Article.objects.get(id=_id, user=request.user)
    context["id"] = _id
    context["ArticleForm"] = ArticleForm(instance=a)

    return render(request, 'upArticle.html', context)


def comment_put(request):

    context = {

        'title': "回复评论"
    }
    _id = request.GET.get("id")
    ar_id = request.GET.get("ar_id")

    print ("===", _id)
    if request.method == "POST":
        _id = request.POST.get("id")

        ar_id = request.POST.get("ar_id")

        content = request.POST.get("content")
        # print ("===ww",_id,ar_id,content)
        a = Article.objects.get(id=ar_id)
        c = comment.objects.get(id=_id)
        print ("ar===", c, a)
        c.replyUser = str(request.user)
        c.status = "p"
        c.reply = content
        c.ArticleComment = a
        c.save()

        return HttpResponse("回复成功")

    # _id=request.GET.get("id")
    # a=Article.objects.get(id=_id,user=request.user)
    context["id"] = _id
    context["ar_id"] = ar_id

    # context["ArticleForm"]=ArticleForm(instance=a)

    return render(request, 'comment_put.html', context)


def chageArticle(request):
    return render(request, 'chageArticle.html', locals())

# def test(request):
#     return render(request, 'registration/password_reset_email.html', locals())


def reg(r):
    status = {}
    status["status"] = True

    if r.method == "POST":
        u = r.POST.get("username")
        p = r.POST.get("password")
        e = r.POST.get("email")
        if u == '' or p == '' or e == '':
            status["status"] = False
            status["msg"] = "注册非法"
            return status

        if MyUser.objects.filter(username=u):
            status["status"] = False
            status["msg"] = "用户存在"
            return status

        if MyUser.objects.filter(email=e):
            status["status"] = False
            status["msg"] = "邮箱存在"
            return status

        _p = re.compile(r'[a-zA-Z].*[0-9]{6,12}')
        if not _p.match(p):
            status["status"] = False
            status["msg"] = "密码不符合要求: 6到12位 大小写字母开头  包含数字"
            return status
        if status["status"] == True:
            MyUser.objects.create_user(username=u, password=p, email=e)
    return status


def register(request):
    context = {
        'page_title': 'user注册',

    }
    s = reg(request)
    print (s)
    if s["status"] == True:
        return redirect("/")
    else:
        return HttpResponse(s["msg"])


def forget(request):

    context = {
        'page_title': '忘记密码'

    }

    return render(request, "admin/forget.html", context)
